/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
var findOrder = function (numCourses, prerequisites) {
  let postOrder = [] // 记录后续遍历的结果
  let hasCycle = false // 初始化没有环
  let visited = new Array(numCourses).fill(false) // 初始化为false
  let onPath = new Array(numCourses).fill(false) // 初始化是不是在路径上
  let graph = new Array(numCourses)
  for (let i = 0; i < numCourses; i++) {
    graph[i] = []
  }
  for (let edge of prerequisites) {
    let from = edge[1]
    let to = edge[0]
    graph[from].push(to) // 将to加入到from对应的数组中 // 下标就是from
  }
  for (let i = 0; i < numCourses; i++) {
    dfs(i) // 对每一个都进行遍历
  }
  if (hasCycle) {
    return [] // 如果有环 就返回空数组
  } else {
    return postOrder.reverse()
  }
  function dfs (s) {
    if (onPath[s]) {
      hasCycle = true
    }
    if (visited[s] || hasCycle) {
      return
    }
    visited[s] = true
    onPath[s] = true
    for (let v of graph[s]) {
      dfs(v)
    }
    postOrder.push(s) // 后续遍历 将这个节点加入到这个后续遍历的数组中
    onPath[s] = false
  }
};
let numCourses = 3, prerequisites = [[1, 0], [2, 0], [0, 2]]
console.log(findOrder(numCourses, prerequisites))